package com.android.manghe.index.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.android.base.tools.DisplayUtil;
import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ScreenUtil;
import com.android.base.tools.StatusBarUtil;
import com.android.manghe.R;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.SimpleWebViewActivity;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.Config;
import com.android.manghe.index.model.FunctionBean;
import com.android.manghe.index.model.MainTopBannerBean;
import com.android.manghe.market.activity.MarketActivity;
import com.android.manghe.mine.activity.MsgTabActivity;
import com.android.manghe.mine.activity.SignActivityBak;
import com.android.manghe.mine.model.UserRes;
import com.android.manghe.search.activity.SearchBigMarketActivity;
import com.android.manghe.user.activity.LoginActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.tmall.ultraviewpager.UltraViewPager;

import java.util.ArrayList;
import java.util.List;

public class TopBannerFunctionsAdapter extends DelegateAdapter.Adapter<TopBannerFunctionsAdapter.TopBannerViewHolder> {

    private Context mContext;
    private List<MainTopBannerBean> mMainTopBannerBeanList = new ArrayList<>();
    private int mCurrentPage;

    private List<FunctionBean> functionBeanList = new ArrayList<>();
    public int itemSize;

    public TopBannerFunctionsAdapter(Context context) {
        mContext = context;
        itemSize = (ScreenUtil.getScreenWidth(mContext) - DisplayUtil.dip2px(mContext, 44)) / 5;
    }

    public void updateFunctionsData(List<FunctionBean> mainBannerList) {
        functionBeanList.clear();
        functionBeanList.addAll(mainBannerList);
        notifyDataSetChanged();
    }

    public void updateBannerData(List<MainTopBannerBean> mainTopBannerBeanList) {
        mCurrentPage = 0;
        mMainTopBannerBeanList.clear();
        mMainTopBannerBeanList.addAll(mainTopBannerBeanList);
        notifyDataSetChanged();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return new LinearLayoutHelper();
    }

    @NonNull
    @Override
    public TopBannerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new TopBannerViewHolder(LayoutInflater.from(mContext)
                .inflate(R.layout.layout_main_top_banner_functions, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull TopBannerViewHolder topBannerViewHolder, int i) {

        //Banner
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.topMargin = StatusBarUtil.getStatusBarHeight(mContext) + 12;
        topBannerViewHolder.itemView.findViewById(R.id.layoutSearch).setLayoutParams(lp);


        topBannerViewHolder.itemView.findViewById(R.id.ivService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserRes.UserInfo userInfo = UserHolder.getUserInfo(mContext);
                set53(mContext, userInfo);
            }
        });
        topBannerViewHolder.itemView.findViewById(R.id.ivNotice).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserRes.UserInfo userInfo = UserHolder.getUserInfo(mContext);
                if (userInfo == null) {
                    mContext.startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    //跳转到消息页面
                    mContext.startActivity(new Intent(mContext, MsgTabActivity.class));
                }
            }
        });
        topBannerViewHolder.itemView.findViewById(R.id.tvSearch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索
                SearchBigMarketActivity.Companion.showActivity(mContext);
            }
        });


        RelativeLayout.LayoutParams re = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        re.topMargin = DisplayUtil.dip2px(mContext, 216);
        re.leftMargin = DisplayUtil.dip2px(mContext, 12);
        re.rightMargin = DisplayUtil.dip2px(mContext, 12);
        re.width = ViewGroup.LayoutParams.MATCH_PARENT;
        re.height = DisplayUtil.dip2px(mContext, functionBeanList.size()>5?186:93);
        re.bottomMargin = DisplayUtil.dip2px(mContext, 10);
        topBannerViewHolder.itemView.findViewById(R.id.id_re).setLayoutParams(re);

        UltraViewPager bannerViewPager = topBannerViewHolder.itemView.findViewById(R.id.bannerViewPager);
        bannerViewPager.setAdapter(new BannerUltraPagerAdapter());
        if (mMainTopBannerBeanList.size() > 0) {
            bannerViewPager.setInfiniteLoop(true);
            bannerViewPager.setAutoScroll(5000);
            bannerViewPager.setCurrentItem(mCurrentPage);
            bannerViewPager.initIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.orange300))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.grey200))
                    .setRadius(DisplayUtil.dip2px(mContext, 4f)).setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 20))
                    .setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)
                    .build();
        } else {
            bannerViewPager.disableIndicator();
            bannerViewPager.setInfiniteLoop(false);
        }
        bannerViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                mCurrentPage = i;
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        //Functions
        UltraViewPager functionViewPager = topBannerViewHolder.itemView.findViewById(R.id.functionViewPager);
        FuncUltraPagerAdapter funcUltraPagerAdapter = new FuncUltraPagerAdapter();
        functionViewPager.setAdapter(funcUltraPagerAdapter);


        if (functionBeanList.size() > 10) {
            functionViewPager.initIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.orange300))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.grey200))
                    .setRadius(DisplayUtil.dip2px(mContext, 4f)).setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 6))
                    .setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)
                    .build();
        } else {
            functionViewPager.disableIndicator();
        }

    }

    @Override
    public int getItemCount() {
        return 1;
    }

    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    class TopBannerViewHolder extends RecyclerView.ViewHolder {

        public TopBannerViewHolder(View itemView) {
            super(itemView);
        }
    }

    private class BannerUltraPagerAdapter extends PagerAdapter {

        public BannerUltraPagerAdapter() {

        }

        @Override
        public int getCount() {
            return mMainTopBannerBeanList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            MainTopBannerBean banner = mMainTopBannerBeanList.get(position);
            ImageView imageView = (ImageView) LayoutInflater.from(container.getContext()).inflate(R.layout.layout_pager_iv_item, null);
            GlideHelper.load(mContext, banner.path, imageView);
            container.addView(imageView);
            imageView.setOnClickListener(TextUtils.isEmpty(banner.link) ? null : new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    WebViewActivity.showActivity(mContext, new WebViewParameter.WebParameterBuilder()
                            .setUrl(banner.link)
                            .setShowProgress(true)
                            .setCanHistoryGoBackOrForward(true)
                            .setReloadable(true)
                            .setReloadType(ERefreshWebType.ClickRefresh)
                            .setCustomTitle(mContext.getString(R.string.app_name))
                            .build());
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ImageView view = (ImageView) object;
            container.removeView(view);
        }
    }

    static class FuncPagerData {
        public List<FunctionBean> list;
    }

    private class FuncUltraPagerAdapter extends PagerAdapter {

        public List<FuncPagerData> funcPagerDataList;

        public FuncUltraPagerAdapter() {
            funcPagerDataList = new ArrayList<>();
            final int PageSize = 10;
            int totalPage = functionBeanList.size() % PageSize == 0 ? functionBeanList.size() / PageSize : functionBeanList.size() / PageSize + 1;
            if (totalPage == 1) {
                FuncPagerData pagerData = new FuncPagerData();
                pagerData.list = functionBeanList;
                funcPagerDataList.add(pagerData);
            } else {
                for (int page = 1; page <= totalPage; page++) {
                    FuncPagerData pagerData = new FuncPagerData();
                    if (page < totalPage) {
                        pagerData.list = functionBeanList.subList((page - 1) * 10, (page - 1) * 10 + 10);
                    } else {
                        pagerData.list = functionBeanList.subList((page - 1) * 10, functionBeanList.size());
                    }
                    funcPagerDataList.add(pagerData);
                }
            }
        }

        @Override
        public int getCount() {
            return funcPagerDataList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            FuncPagerData pagerData = funcPagerDataList.get(position);
            RecyclerView recyclerView = (RecyclerView) LayoutInflater.from(container.getContext()).inflate(R.layout.layout_func_page, null);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 5, LinearLayoutManager.VERTICAL, false);
            recyclerView.setLayoutManager(gridLayoutManager);

            FunctionItemAdapter adapter = new FunctionItemAdapter(mContext, itemSize, pagerData.list);
            recyclerView.setAdapter(adapter);
            container.addView(recyclerView);
            return recyclerView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }


    private class FunctionItemAdapter extends BaseQuickAdapter<FunctionBean, BaseViewHolder> {
        public Context context;
        public int itemSize;

        public FunctionItemAdapter(Context context, int itemSize, List<FunctionBean> list) {
            super(R.layout.item_function, list);
            this.context = context;
            this.itemSize = itemSize;
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, FunctionBean functionBean) {
            GlideHelper.load(context, functionBean.src, R.drawable.default_round, baseViewHolder.getView(R.id.ivIcon));
            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(this.itemSize, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.topMargin=DisplayUtil.dip2px(mContext,10);
            lp.bottomMargin= DisplayUtil.dip2px(mContext,10);
            baseViewHolder.itemView.findViewById(R.id.layoutItem).setLayoutParams(lp);
            baseViewHolder.setText(R.id.tvTitle, functionBean.title);
            baseViewHolder.getView(R.id.ivIcon).setOnClickListener(v -> {
                if (UserHolder.getUserInfo(context) == null) {
                    LoginActivity.Companion.showActivity(context);
                } else {
                    if (functionBean.href != null && !functionBean.href.isEmpty()) {
                        SimpleWebViewActivity.Companion.showActivity(
                                context,
                                functionBean.href,
                                functionBean.title,
                                false
                        );
                        return;
                    }

                    //签到领金币
                    if (!TextUtils.isEmpty(functionBean.id) && functionBean.id.equals("83")) {
                        Intent intent = new Intent(mContext, SignActivityBak.class);
                        mContext.startActivity(intent);
                        return;

                    }

                    //分类页面
                    if (!TextUtils.isEmpty(functionBean.id) && functionBean.id.equals("100")) {
                        Intent intent = new Intent(mContext, MarketActivity.class);
                        intent.putExtra("goodscatid", "");
                        mContext.startActivity(intent);
                        return;
                    }
                    Intent intent = new Intent(mContext, MarketActivity.class);
                    intent.putExtra("goodscatid", !TextUtils.isEmpty(functionBean.goodscatid) ? functionBean.goodscatid : "");
                    mContext.startActivity(intent);

//                    if (!TextUtils.isEmpty(functionBean.goodscatid)) {
//                        Bus.INSTANCE.send(new ShowBigMarketEvent(functionBean.goodscatid));
//                    } else {
//                        //跳转到热门推荐
//                        Bus.INSTANCE.send(new ShowBigMarketEvent(""));
//                    }
                }
            });
        }
    }

    public void set53(Context context, UserRes.UserInfo userInfo) {
        String url = Config.Box_53_URL;
        if (userInfo != null) {
            url = Config.Box_53_URL + Config.Box_53_DEVEICE
                    + String.format(Config.BOX_53_ID, userInfo.UID)
                    + String.format(Config.BOX_53_NAME, userInfo.UID);
        }

        WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                .setUrl(url)
                .setShowProgress(true)
                .setCanHistoryGoBackOrForward(true)
                .setReloadable(true)
                .setShowWebPageTitle(true)
                .setReloadType(ERefreshWebType.ClickRefresh)
                .build();
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        context.startActivity(intent);
    }
}
